from __future__ import absolute_import
import uuid
import random
import datetime
import time
import pymysql
from Call.packaging import user_connect_call
from Forecast_Call.models import Task_Test, Call_List, Seats_Group, Seats_Group_Relevance, Callers_Group, UserCli
from utils.redis_operation import redis_query, redis_save
from utils.connect_mysql import connect_boss,connect_outbound
from celery import shared_task

# 查询未分配被叫号码
def query_call_list(*args,**kwargs):
    task = kwargs.get('task','')
    print('task_id',task)
    # 连接外呼数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select * from zb_call_list where task='%s' and status='1'"%task
        cursor.execute(sql)
        data_list = cursor.fetchall()
        connect.close()
        cursor.close()
        print('call_list',data_list)
        return data_list
    except Exception as e:
        print(e)
        return

# 查询sip账号
def query_sip_number(*args,**kwargs):
    id = kwargs.get('id', '')
    # 连接BOSS数据库
    connect = connect_boss()
    cursor = connect.cursor()
    try:
        sql = "select sipNumber from zb_agentNo where id=%s" % id
        cursor.execute(sql)
        data = cursor.fetchall()
        connect.close()
        cursor.close()
        if not data:
            return ""
        return data[0][0]
    except Exception as e:
        print(e)
        return


# 号码分配坐席
@shared_task
def call_allocation_seats(*args,**kwargs):
    # 开始当前时间
    start_time = kwargs.get('start_time','')
    # # 坐席半小时后无响应释放
    # if datetime.datetime.now() >= start_time + datetime.timedelta(minutes=30):
    #     return
    # 分配坐席方式
    rule = kwargs.get('rule', '')
    # 呼叫方式
    call_way = kwargs.get('call_way', '')
    # 被叫号码信息
    call_list = kwargs.get('call_list',[])
    if not call_list:
        print({"code": 200, "msg": "任务结束"})
        return
    # 坐席信息
    seats_list = kwargs.get('seats_list',[])
    # 随机
    if rule == '1':
        try:
            random.shuffle(seats_list)
            for seats in seats_list:
                seats_number = seats.get('agentNo', '')
                # SIP账号
                sip_number = query_sip_number(id=seats.get('sipAgentNo',''))
                # 查询坐席是否登录
                seats_login = redis_query(key='%s(login)' % seats_number)
                # 查询SIP账号是否已就绪
                sip_online = redis_query(key='%s(online)' % sip_number)
                # 查询坐席是否在忙碌中
                call_busy = redis_query(key='%s(processing)' % seats_number)
                # 就绪
                if seats_login and sip_online and not call_busy:
                    call_number = call_list[0].get('number','')
                    call_list.pop(0)
                    call_pattern(call_way=call_way,seats_number=seats_number,call_number=call_number)
            time.sleep(1)
            call_allocation_seats(start_time=start_time, rule=rule, call_way=call_way, call_list=call_list,
                                        seats_list=seats_list)
        except Exception as e:
            print(str(e))
    # 轮选
    if rule == '2':
        pass
    # 最少
    if rule == '3':
        pass
    # 坐席等级
    if rule == '4':
        pass
    # 空闲时间
    if rule == '5':
        pass



# 呼叫方式
def call_pattern(*args,**kwrags):
    call_way = kwrags.get('call_way','')
    # 直接转坐席
    if call_way == '1':
        seats_number = kwrags.get('seats_number','')
        call_number = kwrags.get('call_number','')
        print(seats_number,call_number)
        res = user_connect_call(userNumber=call_number, userCli="02860695190",userData={'account': '测试账户', 'Apool': '测试A池', 'docking': '测试对接网关', 'ground': '测试落地网关','agent_acc': '测试结算账户', 'userCli': ''}, greetPrompt="", agentNo=seats_number)
        if res.get('code','') == 200:
            # 存储坐席忙碌状态
            redis_save(key='%s(processing)'%seats_number,value='call_%s'%call_number)
            # 存储唯一通话标识
            redis_save(key='%s'%res.get('conversationSid',''),value='%s'%seats_number)
        print(res)
        return res
    # 播放语音任意键转坐席
    if call_way == '2':
        pass
    # 播放语音按键业务场景处理
    if call_way == '3':
        pass
    # 播放语音后挂断
    if call_way == '4':
        pass
    # 播放语音后直接转坐席
    if call_way == '5':
        pass



# 查询所有坐席号
def query_seats_number(*args,**kwargs):
    # 班组ID
    seats_group = kwargs.get('seats_group','')
    # 企业标识
    account_tag = kwargs.get('account_tag','')
    try:
        # 查询所有坐席ID
        seats_list = Seats_Group_Relevance.objects.filter(seats_group=seats_group)
        if not seats_list:
            return []
        # 连接BOOS数据库
        connect = connect_boss()
        cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
        L = []
        for seats_table in seats_list:
            seats = seats_table.seats
            L.append(seats)
        sql = "select a.id,a.sipAgentNo,b.agentNo from zb_job_%s a left join zb_agentNo b on a.sipAgentNo=b.id where find_in_set(a.id,'%s') and a.job_type='1' and sipAgentNo!='0';"%(account_tag,','.join(L))
        cursor.execute(sql)
        data_list = cursor.fetchall()
        connect.close()
        cursor.close()
        return data_list
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# print(query_seats_number(seats_group='2',account_tag='09cccf04966411eb'))

# 侧显号存储
def usercli_save(*args,**kwargs):
    sole_tag = kwargs.get('sole_tag','')
    usercli = kwargs.get('usercli',[])
    try:
        # 查询主叫组ID
        allers_group = Callers_Group.objects.filter(sole_tag=sole_tag).first().id
        for call in usercli:
            UserCli(number=call['tel'],remark=call['udata'],allers_group=allers_group).save()
        return
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# 线索存储
def call_list_save(*args,**kwargs):
    sole_tag = kwargs.get('sole_tag', '')
    call_list = kwargs.get('call_list', [])
    try:
        # 查询主叫组ID
        task = Task_Test.objects.filter(sole_tag=sole_tag).first().id
        for call in call_list:
            Call_List(number=call['tel'],remark=call['udata'],task=task).save()
        return
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# 坐席存储
def seats_save(*args,**kwargs):

    sole_tag = kwargs.get('sole_tag','')
    seats_list = kwargs.get('seats_list','')
    try:
        # 查询班组ID
        seats_group = Seats_Group.objects.filter(sole_tag=sole_tag).first().id
        for seats in seats_list:
            Seats_Group_Relevance(seats_group=seats_group,seats=seats).save()
        return
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# 创建主叫分组
def create_callers_group(*args,**kwargs):
    group_name = kwargs.get('group_name', '')
    strategy = kwargs.get('strategy', '')
    usercli = kwargs.get('usercli', [])
    sole_tag = uuid.uuid1()
    try:
        Callers_Group(group_name=group_name,strategy=strategy,sole_tag=sole_tag).save()
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","e":str(e)}
    # 存储侧显号列表
    res = usercli_save(sole_tag=sole_tag, usercli=usercli)
    if res:
        return res
    return {"code":200,"msg":"创建成功"}

# 创建任务
def create_task(*args,**kwargs):
    # 任务名称
    task_name = kwargs.get('task_name','')
    # 线索列表
    call_list = kwargs.get('call_list','')
    # 呼叫方式
    call_way = kwargs.get('call_way','')
    # 班组id
    queue_id = kwargs.get('queue_id','')
    # 任务优先级
    priority = kwargs.get('priority')
    # 任务开始时间
    start_time = kwargs.get('start_time')
    # 任务结束时间
    end_time = kwargs.get('end_time')
    # 用户主叫标识分组
    callers_group = kwargs.get('callers_group','')
    # 模板外键
    template = kwargs.get('template')
    # 并发
    concurrence = kwargs.get('concurrence')
    # 状态
    status = kwargs.get('status')
    # 备注
    remark = kwargs.get('remark')
    # 唯一标识
    sole_tag = uuid.uuid1()
    task_test = Task_Test(task_name=task_name,call_way=call_way,queue_id=queue_id,priority=priority,start_time=start_time,end_time=end_time,callers_group=callers_group,template=template,concurrence=concurrence,status=status,remark=remark,sole_tag=sole_tag)
    try:
        task_test.save()
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}
    # 保存线索
    res = call_list_save(sole_tag=sole_tag,call_list=call_list)
    if res:
        return res
    return {"code":200,"msg":"创建成功"}

# 创建班组
def create_seats_group(*args,**kwargs):
    group_name = kwargs.get('group_name','')
    group_leader = kwargs.get('group_leader','')
    rule = kwargs.get('rule','')
    status = kwargs.get('status','')
    remark = kwargs.get('remark','')
    seats_list = kwargs.get('seats_list',[])
    if not seats_list:
        return {"code": 403, "msg": "至少分配一个坐席"}
    account_tag = kwargs.get('account_tag','')
    # 唯一标识
    sole_tag = uuid.uuid1()
    try:
        Seats_Group(group_name=group_name,group_leader=group_leader,rule=rule,status=status,remark=remark,sole_tag=sole_tag,account_tag=account_tag).save()
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}
    # 保存坐席及班组关系
    res = seats_save(sole_tag=sole_tag,seats_list=seats_list)
    if res:
        return res
    return {"code": 200, "msg": "创建成功"}


# 开始任务
@shared_task
def start_task_test(*args,**kwargs):
    # 任务ID
    task_id = kwargs.get('task_id','')
    # 企业标识
    account_tag = kwargs.get('account_tag','')
    try:
        # 查询任务信息
        task = Task_Test.objects.filter(id=task_id).first()
        # 查询班组信息
        seats_group = Seats_Group.objects.filter(id=task.queue_id).first()
        # 班组是否激活状态
        if seats_group.status != '1':
            return {"code": 403, "msg": "班组未激活"}
        # 任务是否启动状态
        if task.status != '1':
            return {"code": 403, "msg": "请开启此任务"}
        # 查询所有被叫号码
        call_list = query_call_list(task=task_id)
        if not call_list:
            return {"code": 403, "msg": "请上传被叫号码"}
        # 查询对应的所有坐席信息
        seats_list = query_seats_number(seats_group=task.queue_id,account_tag=account_tag)
        if not seats_list:
            return {"code":403,"msg":"请分配坐席"}
        # 分配号码
        call_allocation_seats.delay(start_time=datetime.datetime.now(),rule=seats_group.rule,call_way=task.call_way,call_list=call_list,seats_list=seats_list)
        return {"code":200,"msg":"启动成功"}
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# print(start_task_test(task_id='1',account_tag='09cccf04966411eb'))